package com.sk.weichat.ui.me.wallet;

import android.arch.lifecycle.Observer;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.security.rp.RPSDK;
import com.sk.weichat.AppConfig;
import com.sk.weichat.AppConstant;
import com.sk.weichat.R;
import com.sk.weichat.bean.WalletInfoBean;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.ui.WebAgreementActivity;
import com.sk.weichat.ui.base.BaseLoginActivity;
import com.sk.weichat.ui.me.SmsCodeForIdentifyActivity;
import com.sk.weichat.ui.me.wallet.view.RealNameAuthenticationView;
import com.sk.weichat.ui.me.wallet.viewmode.RealNameAuthenticationViewMode;
import com.sk.weichat.ui.tool.WebViewActivity;
import com.sk.weichat.util.LiveDataBus;
import com.sk.weichat.util.ScreenUtil;
import com.sk.weichat.util.ToastUtil;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import okhttp3.Call;

import static com.sk.weichat.ui.me.wallet.RechargeActivity.event_recharge_success;

public class MyWalletActivity extends BaseLoginActivity implements View.OnClickListener, RealNameAuthenticationView {
    //设置密码短信验证身份
    //private static final int request_sms_for_set_pay_pswd = 6372;
    //忘记密码短信验证身份
    //private static final int request_sms_for_forget_pay_pswd = 4781;

    //忘记密码支付宝授权
    private static final String request_alipay_auth_for_forget_pay_pswd_event = "request_alipay_auth_for_forget_pay_pswd_event";


    private String eventForgetPwd = "eventForgetPwd";
    private String eventSetPwd = "eventSetPwd";

    private ImageView ivBack;
    private TextView tvMoney;
    private TextView tvRealNameAuth;
    private TextView tvAlipayAuth;
    private TextView tvIdentify;
    private TextView tvAlipay;
    private TextView tvSetPswdPpay;
    private TextView tvReset;
    private TextView tvRecharge;
    private TextView tvWithdraw;
    private TextView tvForgetPswd;
    private TextView tvTradeRecode;

    private WalletInfoBean mWalletInfoBean;

    private RealNameAuthenticationViewMode mRealNameAuthenticationViewMode;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_wallet);
        getSupportActionBar().hide();
        initView();
        onLoadWalletInfo();
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    private void initView() {
        ivBack = findViewById(R.id.iv_back);
        tvMoney = findViewById(R.id.tv_money);
        tvRealNameAuth = findViewById(R.id.tv_real_name_auth);
        tvAlipayAuth = findViewById(R.id.tv_alipay_auth);
        tvIdentify = findViewById(R.id.tv_identify);
        tvSetPswdPpay = findViewById(R.id.tv_set_pswd_for_pay);
        tvAlipay = findViewById(R.id.tv_alipay);
        tvReset = findViewById(R.id.tv_reset);
        tvRecharge = findViewById(R.id.tv_recharge);
        tvWithdraw = findViewById(R.id.tv_withdraw);
        tvForgetPswd = findViewById(R.id.tv_forget_pswd);
        tvTradeRecode = findViewById(R.id.tv_trade_record);
        tvTradeRecode.setOnClickListener(this);
        tvForgetPswd.setOnClickListener(this);
        tvRecharge.setOnClickListener(this);
        tvWithdraw.setOnClickListener(this);
        ivBack.setOnClickListener(this);
        tvIdentify.setOnClickListener(this);
        tvAlipay.setOnClickListener(this);
        tvReset.setOnClickListener(this);
        tvSetPswdPpay.setOnClickListener(this);
        int statusbar_height = 0;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            statusbar_height = ScreenUtil.getStatusHeight(mContext);
        }
        ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) ivBack.getLayoutParams();
        lp.topMargin += statusbar_height;
        ivBack.setLayoutParams(lp);
//
        mRealNameAuthenticationViewMode = new RealNameAuthenticationViewMode(coreManager, this);

        LiveDataBus.get().with(eventForgetPwd).observe(this, new Observer<Object>() {
            @Override
            public void onChanged(@Nullable Object o) {
                //
                //忘记支付密码
                if (mWalletInfoBean != null && mWalletInfoBean.getSetPayPasswordType().equals(AppConstant.SET_PAY_PASSWORD_TYPE_ALIYUN)) {
                    //未绑定支付宝,通过回答问题
                    Intent intent = new Intent(mContext, IdentifyThroughAnswerQuestionActivity.class);
                    intent.putExtra("AlipayName", mWalletInfoBean.getAliPayNickName());
                    mContext.startActivity(intent);
                } else if (mWalletInfoBean != null && mWalletInfoBean.getSetPayPasswordType().equals(AppConstant.SET_PAY_PASSWORD_TYPE_ALIPAY)) {
                    //绑定了支付宝,重新吊起授权
                    AlipayAuthActivity.startAlipayAuthActivity(mWalletInfoBean.getAliPayNickName(), request_alipay_auth_for_forget_pay_pswd_event, MyWalletActivity.this);
                }
            }
        });

        LiveDataBus.get().with(eventSetPwd).observe(this, new Observer<Object>() {
            @Override
            public void onChanged(@Nullable Object o) {
                if (mWalletInfoBean != null) {
                    //设置支付密码
                    startActivity(new Intent(mContext, SetpswAuthenticationActivity.class).putExtra("RealNameAuthStatus", mWalletInfoBean.getRealNameAuthStatus()));
                }
            }
        });


        LiveDataBus.get().with(request_alipay_auth_for_forget_pay_pswd_event).observe(this, new Observer<Object>() {
            @Override
            public void onChanged(@Nullable Object o) {
                //忘记密码支付宝验证成功
                startActivity(new Intent(mContext, ResetPayPwdNewActivity.class));
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v == ivBack) {
            finish();
        } else if (v == tvIdentify) {//实名认证
            if (mWalletInfoBean != null && mWalletInfoBean.getRealNameAuthStatus() == 0) {
                // 获取阿里云实名认证token
                mRealNameAuthenticationViewMode.getAliyunToken();
            } else if (mWalletInfoBean != null) {
                startActivity(new Intent(this, IDInformationActivity.class)
                        .putExtra("name", mWalletInfoBean.getName())
                        .putExtra("idCard", mWalletInfoBean.getIdCard())
                        .putExtra("cardType", mWalletInfoBean.getCardType()));
            }
        } else if (v == tvAlipay) {//支付宝绑定
            if (mWalletInfoBean != null) {
                startActivity(new Intent(this, IdentityAuthenticationActivity.class)
                        .putExtra("aliPayNickName", mWalletInfoBean.getAliPayNickName()));
            }
        } else if (v == tvSetPswdPpay) {//设置密码  发送验证码认证
            //设置密码
            SmsCodeForIdentifyActivity.startSmsCodeForIdentifyActivity(eventSetPwd, mContext);
        } else if (v == tvReset) {
            if (mWalletInfoBean != null) {
                //重置密码
                startActivity(new Intent(this, ResetPayPwdOldActivity.class)
                        .putExtra("aliPayNickName", mWalletInfoBean.getAliPayNickName()));
            }
        } else if (v == tvRecharge) {
            //充值
            startActivity(new Intent(mContext, RechargeActivity.class));
        } else if (v == tvWithdraw) {
            showLoadFailMsg("提现功能正努力开发中");
        } else if (v == tvForgetPswd) {
            //忘记密码
            SmsCodeForIdentifyActivity.startSmsCodeForIdentifyActivity(eventForgetPwd, mContext);
        } else if (v == tvTradeRecode) {
            //交易记录
            String url = coreManager.getConfig().TRADE_RECORDE + "?access_token=" + coreManager.getSelfStatus().accessToken + "&time=" + System.currentTimeMillis() / 1000;
            goToWeb(url);
        }
    }

    private void goToWeb(String url) {
        Intent intent = new Intent(mContext, WebViewActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("feedback", true);
        startActivity(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    //四舍五入
    NumberFormat numberFormat = new DecimalFormat("###,###,###,##0.00");

    /**
     * 获取钱包信息
     */
    public void onLoadWalletInfo() {
        //showProgress();
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        HttpUtils.post().url(coreManager.getConfig().WALLET_INFO)
                .params(params)
                .build()
                .execute(new BaseCallback<WalletInfoBean>(WalletInfoBean.class) {

                    @Override
                    public void onResponse(ObjectResult<WalletInfoBean> result) {
                        if (result.getResultCode() == 1 && result.getData() != null) {
//                            hideProgress();
                            mWalletInfoBean = result.getData();
                            String money = numberFormat.format(mWalletInfoBean.getBalance());
                            tvMoney.setText(money);
                            if (mWalletInfoBean.getRealNameAuthStatus() == 0) {
                                tvRealNameAuth.setText(getString(R.string.please_go_auth));
                            } else {
                                tvRealNameAuth.setText(getString(R.string.authenticated));
                            }
                            if (TextUtils.isEmpty(mWalletInfoBean.getAliPayNickName())) {
                                tvAlipayAuth.setText(getString(R.string.please_bind_alipay));
                                tvAlipayAuth.setTextColor(getResources().getColor(R.color.color_919298));

                            } else {
                                tvAlipayAuth.setText(mWalletInfoBean.getAliPayNickName());
                                tvAlipayAuth.setTextColor(getResources().getColor(R.color.color_FF27A2FF));
                            }

                            if (mWalletInfoBean.getHavePayPassword() == 0) {//未设置支付密码
                                tvSetPswdPpay.setVisibility(View.VISIBLE);
                                tvReset.setVisibility(View.GONE);
                                tvForgetPswd.setVisibility(View.GONE);
                            } else {//已设置支付密码
                                tvSetPswdPpay.setVisibility(View.GONE);
                                tvReset.setVisibility(View.VISIBLE);
                                tvForgetPswd.setVisibility(View.VISIBLE);
                            }
                        } else {
                            //hideProgress();
                            //showLoadFailMsg(result.getResultMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        Log.e("WalletInfo", "Exception", e);
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(String str) {
        //绑定或解绑成功  重新获取钱包数据刷新
        if (str.equals("bind_success") || str.equals("unbind_success")
                || str.equals("set_pay_psd_success") || str.equals("auth_success")
                || str.equals(event_recharge_success)) {
            onLoadWalletInfo();
        }
    }

    /**
     * 取阿里云token 结果返回
     */
    @Override
    public void getAliyunTokenResult(ObjectResult<String> reslut) {
        if (reslut.getResultCode() == 1) {
            RPSDK.start(reslut.getData(), MyWalletActivity.this,
                    new RPSDK.RPCompletedListener() {
                        @Override
                        public void onAuditResult(RPSDK.AUDIT audit, String code) {
                            // 认证通过时code="",所以传1过去给后台哥们判断
                            String authCode = TextUtils.isEmpty(code) ? "1" : code;
                            //上传阿里云实名认证结果
                            mRealNameAuthenticationViewMode.AiyunAuthBack(authCode);
                          /*  if (audit == RPSDK.AUDIT.AUDIT_PASS) { //认证通过
                                mRealNameAuthenticationViewMode.AiyunAuthBack(code);
                            } else if (audit == RPSDK.AUDIT.AUDIT_FAIL) { //认证不通过
                                mRealNameAuthenticationViewMode.AiyunAuthBack("2");
//                                ToastUtil.showToast(MyWalletActivity.this, R.string.auth_fail);
                            } else if (audit == RPSDK.AUDIT.AUDIT_NOT) { //未认证，具体原因可通过code来区分（code取值参见下方表格），通常是用户主动退出或者姓名身份证号实名校验不匹配等原因，导致未完成认证流程
//                                ToastUtil.showToast(MyWalletActivity.this, R.string.auth_cancle);
                                mRealNameAuthenticationViewMode.AiyunAuthBack(code);
                            }*/
                        }
                    });
        } else {
            ToastUtil.showToast(this, reslut.getResultMsg());
        }
    }

    /**
     * 上传阿里云授权状态回调后台接口 返回结果
     */
    @Override
    public void AiyunAuthBackResult(ObjectResult<String> result) {
        if (result.getResultCode() == 1) {
            onLoadWalletInfo();
        }
        showLoadFailMsg(result.getResultMsg());
    }

    @Override
    public void showProgress() {
        if (!DialogHelper.isShowing()) {
            DialogHelper.showDefaulteMessageProgressDialog(this);
        }
    }

    @Override
    public void hideProgress() {
        DialogHelper.dismissProgressDialog();
    }

    @Override
    public void showLoadFailMsg(String err) {
        ToastUtil.showToast(this, err);
    }

}
